package com.health.controller;

import com.health.common.Result;
import com.health.entity.Doctor;
import com.health.entity.pojo.PageData;
import com.health.entity.pojo.dto.DoctorDTO;
import com.health.entity.pojo.vo.ConsultingroomVO;
import com.health.entity.pojo.vo.DoctorVO;
import com.health.mapper.DoctorMapper;
import com.health.service.IDoctorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cl
 * @since 2023-04-15
 */
@Api(tags = "医生管理")
@RestController
@RequestMapping("/doctor")
public class DoctorController extends BaseController {
    @Autowired
    IDoctorService doctorService;
    @Autowired
    DoctorMapper doctorMapper;

    Doctor doctor = null;

    @PostMapping("/listDoctor/{pageNum}/{pageSize}")
    @ApiOperation("[分页]根据条件-展示(查询)医生")
    public Result queryDoctor(@PathVariable("pageNum") Integer pageNum,
                              @PathVariable("pageSize") Integer pageSize,
                              @RequestBody DoctorDTO dto) {
        System.out.println("后端接收到的DTO为——————————>" + dto);
        PageData dividePageData = doctorService.listDoctorByPageAndCondition(pageNum, pageSize, dto);
        System.out.println("后端经过动态SQL进行条件查询所得的dividePageData为 ===============> " + dividePageData.getList());
        return dividePageData == null ? Result.error(500, "未知错误！") : Result.success(200, "", dividePageData);
    }

    @DeleteMapping("/deleteDoctor")
    @ApiOperation("【删除】按钮触发——批量[删除]")
    public Result deleteDoctor(@RequestBody Integer... ids) {
//        int delNum = 0;
//        QueryWrapper<Doctor> wrapper = null;
//        for ( Integer i : ids ) {
//            wrapper = new QueryWrapper<>();
//            wrapper.eq(id,i);                     //【问】
//
//            boolean b = doctorService.remove(wrapper);
//            if (b) delNum ++ ;
//        }
//        if (delNum == ids.length) return Result.error(200,"批量删除成功，共删除了"+ids.length+"条数据...");
//        return delNum < ids.length ? Result.error(500,"批量删除失败！本次共删除"+delNum+"条数据，请尝试手动删除剩余数据") : Result.error(500,"未知错误！请重试");
        List<Integer> arrToList = new ArrayList<>();
//        BeanUtils.copyProperties(ids,arrToList);          //【易错】
        for (Integer i : ids) {
            arrToList.add(i);
        }
//        return ids.length>1 ? booleanResult( doctorService.removeBatchByIds(ids) ) :
        return arrToList.size() > 1 ? booleanResult(doctorService.removeBatchByIds(arrToList)) : booleanResult(doctorService.removeById(ids[0]));
    }

    @GetMapping("/getDoctorById/{id}")
    @ApiOperation("【查看详情】触发——根据医生id展示该医生的数据、【编辑】'医生'触发——根据该页面接收的医生的编号id查询出该医生的数据")
    public Result getDoctor(@PathVariable("id") Integer id) {
//        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
//        wrapper.eq(id,id);            //【问】
        System.out.println("后端已收到[查询(展示)]id值=" + id + "的医生数据");
        Doctor doctor = doctorService.getById(id);
        DoctorVO doctorVO = new DoctorVO();

        BeanUtils.copyProperties(doctor, doctorVO);

        doctorVO.setDoctorId(doctor.getId());
        doctorVO.setDoctorName(doctor.getName());
        doctorVO.setDoctorAvatar(doctor.getAvatar());
        doctorVO.setDoctorTitle(doctor.getTitle());
        //接收前端传递到此的'二级科室'的id值并存入doctorVO内
        doctorVO.setChildId(doctor.getConsultingroomId().longValue());
        //[添加/修改]、[编辑]医生时，根据'二级科室'的编号id值，查询出其所属'一级科室'的编号id值
        Integer oneId = doctorMapper.getOneId(doctorVO.getChildId());
        doctorVO.setParentId(oneId);
        //根据查出的一级科室的id值、二级科室的id值，查询出一级科室、二级科室的名称
        String parentName = doctorMapper.getParentConsultingroomName(doctorVO.getParentId());//查出一级科室名称
        String childName = doctorMapper.getChildConsultingroomName(doctorVO.getChildId());//查出二级科室名称
        doctorVO.setParentConsultingroom(parentName);
        doctorVO.setChildConsultingroom(childName);

        return doctor == null ? Result.error(500, "获取失败！请重试") : dataResult(doctorVO);
    }

    @PostMapping("/addOrEditDoctor")
    @ApiOperation("【确定添加/修改】按钮触发")
    public Result addOrUpdateDoctor(@RequestBody DoctorDTO auDTO) {
        System.out.println("后端已收到[添加/修改]" + auDTO + "的请求");
        doctor = new Doctor();
        BeanUtils.copyProperties(auDTO, doctor);

        doctor.setId(auDTO.getDoctorId());          //【关键步骤：否则执行"修改"时，由于实体类变量doctor拿不到id值从而执行“添加”】
        doctor.setName(auDTO.getDoctorName());
        doctor.setAvatar(auDTO.getDoctorAvatar());
        doctor.setTitle(auDTO.getDoctorTitle());
        doctor.setConsultingroomId(auDTO.getChildId().intValue());    //Long类型强转为Integer类型
        boolean b = doctorService.saveOrUpdate(doctor);
        return b == false ? Result.error(500, "操作失败") : Result.success(200, "操作成功");
    }

    @GetMapping("/getAllHospital")
    @ApiOperation("[添加/编辑]医生时，为'所属医院'下拉框赋值([展示](查询)出所有医院id、名字")
    public Result getHospital() {
        List<Doctor> hospitalNameAnId = doctorService.getAllHospitalNameAndId();
        return hospitalNameAnId.isEmpty() ? Result.error(500, "无数据！") : Result.success(200, "", hospitalNameAnId);
    }

    @GetMapping("/getAllConsultingRoom/{parentId}")
    @ApiOperation("[添加/编辑]医生时，为'所属科室'下拉框(2个)分别赋值([展示](查询)出所有一级科室及其对应的二级科室")
    public Result getAllParentConsultingRoom(@PathVariable("parentId") Long parent_id) {
        System.out.println("后端已收到[展示](查询)出所有一级科室编号parent_id值= " + parent_id + "及其对应的二级科室的请求");
        List<ConsultingroomVO> consultingroomVOList = doctorService.getAllConsultingRoom(parent_id);
        return consultingroomVOList.isEmpty() ? Result.error(500, "") : Result.success(200, "", consultingroomVOList);
    }

    @GetMapping("/changeStatus/{shelf}/{doctorId}")
    @ApiOperation("【是否上架】按钮触发")
    public Result changeStatusOnOrOff(@PathVariable("shelf") Boolean isShelf, @PathVariable("doctorId") Integer did) {
        System.out.println("后端已收到【是否上架】按钮所触发将id值= " + did + "的数据，根据其对应的isShelf的值 = " + isShelf + "进行[上架(0)/下架(1)]操作的请求");
        System.out.println( "前端传送到此的参数isShelf的类型为------>" + isShelf.getClass() );
        Integer row = doctorMapper.changeStatus(isShelf ? 0 : 1, did);
        return row < 1 ? Result.error(500, "操作失败") : Result.error(200, "操作成功");
    }
    @PutMapping("/changeStatusOnOrOff/{shelf}")
    @ApiOperation("【上架】、【下架】按钮——共同触发")
    public Result updateStatusOnOrOff(@PathVariable("shelf") Boolean isShelf, @RequestBody Integer...idOrIds){
        System.out.println("后端已收到【是否上架】按钮所触发将id值= " + idOrIds + "的数据，根据其对应的isShelf的值 = " + isShelf + "进行[上线/下线]操作的请求");
        int changeLoadNum = 0;
        for (Integer i : idOrIds) {
            System.out.println("--------->"+ i);
            Doctor doctor = doctorService.getById(i);
            if (doctor == null)     continue;
            //               isShelf == false ? doctor.setStatus( byte(1) ) : doctor.setStatus( (byte)0 );     //【问？为何三元此处不行？】
//               if ( false == isShelf ) {
//                   doctor.setStatus((byte) 1);         //【易错：set方法改变的值并未入MySQL库内！】
//                   changeLoadNum++;
//               }
//               isShelf == false ? doctorMapper.changeStatus(1) : doctorMapper.changeStatus(0);   //【问？为何三元此处不行？】
            doctorMapper.changeStatus( !isShelf ? 1 : 0,  i );
            changeLoadNum ++;
        }
        return changeLoadNum < idOrIds.length ? Result.error(500, "执行成功，但有" + (idOrIds.length - changeLoadNum) + "个操作失败！请尝试手动上架这些") : Result.error(200, "批量操作成功");
    }

}
